package App.Controller;

import App.Model.BaseEnum;
import App.Model.BaseResponse;
import App.Model.Chat.*;
import App.Model.DataResponse;
import App.Model.Project.ProjectMember;
import App.Model.Project.ProjectMemberGetRequest;
import App.Model.Tecent.TecentIMConfig;
import App.Service.AccountService;
import App.Service.ChatService;
import App.Service.ProjectService;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by xw on 2018/11/21.
 */

@RestController
@RequestMapping("/api/chat/")
public class ChatController extends BaseController {
    @Autowired
    private TecentIMConfig _imConfig;

    @Autowired
    private ChatService _chatService;

    @Resource
    private AccountService _accountService;

    @Autowired
    private ProjectService _projectService;

    @RequestMapping(value = "group", method = RequestMethod.POST)
    public ResponseEntity<?> getChatGroup() {
        DataResponse _dataResponse = new DataResponse();
        try {
            ChatGroupRequest _request = new ChatGroupRequest();
//            _request.setPageindex(1);
//            _request.setPagesize(20);
            ChatGroupResponse result = _chatService.getGroupList(_request, userId());
            _dataResponse.setData(result.getDatalist());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new ResponseEntity(_dataResponse, HttpStatus.OK);
    }
    @RequestMapping(value = "v3/group", method = RequestMethod.POST)
    public ResponseEntity<?> getChatGroupV3(@RequestBody(required = false) ChatGroupRequest _request) {
        DataResponse _dataResponse = new DataResponse();
        try {
            if (_request == null) {
                _request = new ChatGroupRequest();
            }
            if (_request.getPageindex() == 0) {
                _request.setPageindex(1);
            }
            if (_request.getPagesize() == 0) {
                _request.setPagesize(20);
            }
            ChatGroupResponse result = _chatService.getGroupListByPageV3(_request, userId());
            _dataResponse.setData(result.getDatalist());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new ResponseEntity(_dataResponse, HttpStatus.OK);
    }

    @RequestMapping(value = "v2/group", method = RequestMethod.POST)
    public ResponseEntity<?> getChatGroupV2(@RequestBody(required = false) ChatGroupRequest _request) {
        DataResponse _dataResponse = new DataResponse();
        try {
            if (_request == null) {
                _request = new ChatGroupRequest();
            }
            if (_request.getPageindex() == 0) {
                _request.setPageindex(1);
            }
            if (_request.getPagesize() == 0) {
                _request.setPagesize(20);
            }
//            if(_request.getPageindex() > 1){
//                _request.setPagesize(30);
//            }
            ChatGroupResponse result = _chatService.getGroupListV2(_request, userId());
            _dataResponse.setData(result.getDatalist());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new ResponseEntity(_dataResponse, HttpStatus.OK);
    }

    @RequestMapping(value = "stagegroup/{groupid}")
    public ResponseEntity<?> getStageGroup(@PathVariable String groupid) {
        DataResponse _dataResponse = new DataResponse();
        try {
            ChatGroupListResponse stageGroup = _chatService.getStageGroup(groupid, userId());
            _dataResponse.setData(stageGroup);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return new ResponseEntity(_dataResponse, HttpStatus.OK);
    }

    @RequestMapping("stage")
    public ResponseEntity<?> getChatStage(@RequestBody(required = false) ChatStageGetRequest _request) {
        DataResponse _dataResponse = new DataResponse();
        try {
            List<ChatStage> _stages = _chatService.getChatStage(_request, userId());
            _dataResponse.setData(_stages);
        } catch (Exception ex) {
            ex.printStackTrace();
            _dataResponse.setData(ex);
        }
        return new ResponseEntity(_dataResponse, HttpStatus.OK);
    }

    /*
    @RequestMapping("topic")
    public ResponseEntity<?> getChatTopic(@RequestBody(required = false) ChatGetTopicRequest _request) {
        DataResponse _dataResponse = new DataResponse();
        try {
            List<ChatTopic> _stages = _chatService.getChatTopic(_request);
            _dataResponse.setData(_stages);
        } catch (Exception ex) {

            ex.printStackTrace();
            // return null;
        }
        return new ResponseEntity(_dataResponse, HttpStatus.OK);
    }
*/

    //勾选，或者取消勾选聊挺主题
    @RequestMapping("checktopic")
    public ResponseEntity<?> checkTopic(@RequestBody(required = false) ChatCheckTopicRequest _request) {

        BaseResponse _baseResponse = new BaseResponse();
        if (_request == null) {
            _baseResponse = ResponseError(null, "参数格式错误");
            return new ResponseEntity(_baseResponse, HttpStatus.OK);
        }
        try {
            int result = _chatService.checkTopic(_request, userId());
            _baseResponse = ResponseError(null, "参数格式错误");
            _baseResponse.setMessage("操作失败");
            _baseResponse.setSuccess(BaseEnum.ApiResult.Failure.getApiResult());

            if (result > 0) {
                _baseResponse.setMessage("操作成功");
                _baseResponse.setSuccess(BaseEnum.ApiResult.Success.getApiResult());
            }
            return new ResponseEntity(_baseResponse, HttpStatus.OK);
        } catch (Exception ex) {
            ex.printStackTrace();
            _baseResponse.setData(ex);
            return new ResponseEntity(_baseResponse, HttpStatus.OK);
        }
    }


    //推进到下一个阶段
    @RequestMapping("nextstage")
    public ResponseEntity<?> toNextStage(@RequestBody(required = false) ChatNextStageRequest _request) {
        if (_request == null) {
            BaseResponse _baseResponse = ResponseError(null, "参数格式错误");
            return new ResponseEntity(_baseResponse, HttpStatus.OK);
        }
        DataResponse _dataResponse = new DataResponse();
        try {
            ChatGroupDetailResponse _result = _chatService.toNextStage(_request, userId());
            _dataResponse.setData(_result);
        } catch (Exception ex) {
            ex.printStackTrace();
            _dataResponse.setData(ex.getMessage());
        }
        return new ResponseEntity(_dataResponse, HttpStatus.OK);
    }

    //获取某个阶段的数据
    @RequestMapping("stagedetail")
    public ResponseEntity<?> getStageDetail(@RequestBody(required = false) ChatStageDetailRequest _request) {
        if (_request == null) {
            BaseResponse _baseResponse = ResponseError(null, "参数格式错误");
            return new ResponseEntity(_baseResponse, HttpStatus.OK);
        }
        DataResponse _dataResponse = new DataResponse();
        try {
            ChatGroupDetailResponse _result = _chatService.getStageDetail(_request, userId());
            _dataResponse.setData(_result);
        } catch (Exception ex) {
            ex.printStackTrace();
            _dataResponse.setData(ex.getMessage());
        }
        return new ResponseEntity(_dataResponse, HttpStatus.OK);
    }

    @RequestMapping("detail")
    public ResponseEntity<?> getChatGroupDetail(@RequestBody(required = false) ChatGroupDetailRequest _request) {
        DataResponse _dataResponse = new DataResponse();
        try {
            ChatGroupDetailResponse _result = _chatService.getGroupDetail(_request);
            _dataResponse.setData(_result);
        } catch (Exception ex) {
            _dataResponse.setData(ex);
            ex.printStackTrace();
        }
        return new ResponseEntity(_dataResponse, HttpStatus.OK);
    }

    @RequestMapping("member")
    public ResponseEntity<?> getChatMember(@RequestBody(required = false) ProjectMemberGetRequest _request) {
        DataResponse _dataResponse = new DataResponse();
        try {

            List<ProjectMember> _result = _projectService.getProjectMember(_request);
            _dataResponse.setData(_result);
        } catch (Exception ex) {
            _dataResponse.setData(ex);
            ex.printStackTrace();
        }
        return new ResponseEntity(_dataResponse, HttpStatus.OK);
    }

    //发送消息
    @RequestMapping("send")
    public ResponseEntity<?> sendMessage(@RequestBody(required = false) ChatSendRequest _request) {
        BaseResponse _baseResponse = new BaseResponse();
        if (_request == null) {
            _baseResponse = ResponseError(null, "参数格式错误");
            return new ResponseEntity(_baseResponse, HttpStatus.OK);
        }
        try {
            int result = _chatService.chatSend(_request, userId());
            _baseResponse = ResponseError(null, "参数格式错误");
            _baseResponse.setMessage("操作失败");
            _baseResponse.setSuccess(BaseEnum.ApiResult.Failure.getApiResult());

            if (result > 0) {
                _baseResponse.setMessage("操作成功");
                _baseResponse.setSuccess(BaseEnum.ApiResult.Success.getApiResult());
            }
            return new ResponseEntity(_baseResponse, HttpStatus.OK);

        } catch (Exception ex) {
            _baseResponse.setData(ex);
            ex.printStackTrace();
        }
        return new ResponseEntity(_baseResponse, HttpStatus.OK);
    }

    //获取消息
    @RequestMapping("message")
    public ResponseEntity<?> getMessage(@RequestBody(required = false) ChatGetMessageRequest _request) {
        DataResponse _dataResponse = new DataResponse();
        try {
            List<ChatMessage> _result = _chatService.getChatMessage(_request, userId());
            _dataResponse.setData(_result);
        } catch (Exception ex) {
            ex.printStackTrace();
            _dataResponse.setData(ex);
        }
        return new ResponseEntity(_dataResponse, HttpStatus.OK);
    }

    //发送消息
    @RequestMapping("addgroup")
    public ResponseEntity<?> addGroup(@RequestBody(required = false) ChatSendRequest _request) {

        BaseResponse _baseResponse = new BaseResponse();
        if (_request == null) {
            _baseResponse = ResponseError(null, "参数格式错误");
            return new ResponseEntity(_baseResponse, HttpStatus.OK);
        }
        try {
            int result = _chatService.chatSend(_request, userId());

            _baseResponse = ResponseError(null, "参数格式错误");
            _baseResponse.setMessage("操作失败");
            _baseResponse.setSuccess(BaseEnum.ApiResult.Failure.getApiResult());

            if (result > 0) {
                _baseResponse.setMessage("操作成功");
                _baseResponse.setSuccess(BaseEnum.ApiResult.Success.getApiResult());
            }
            return new ResponseEntity(_baseResponse, HttpStatus.OK);

        } catch (Exception ex) {
            ex.printStackTrace();
            _baseResponse.setData(ex);
            return new ResponseEntity(_baseResponse, HttpStatus.OK);
        }
    }

    @RequestMapping("search")
    public ResponseEntity<?> searchGhat(@RequestBody(required = false) ChatSearchRequest _request) {
        if (_request == null) {
            BaseResponse _baseResponse = ResponseError(null, "参数格式错误");
            return new ResponseEntity(_baseResponse, HttpStatus.OK);
        }
        DataResponse _dataResponse = new DataResponse();
        try {
            List<ChatGroup> _result = _chatService.searchChat(_request, userId());
            _dataResponse.setData(_result);
        } catch (Exception ex) {
            ex.printStackTrace();
            _dataResponse.setData(ex.getMessage());
        }
        return new ResponseEntity(_dataResponse, HttpStatus.OK);
    }

    //启动分支
    @RequestMapping("startbranch")
    public ResponseEntity<?> startChatBranchStage(@RequestBody(required = false) ChatBranchStageRequest _request) {
        BaseResponse _baseResponse = new BaseResponse();
        if (_request == null) {
            _baseResponse = ResponseError(null, "参数格式错误");
            return new ResponseEntity(_baseResponse, HttpStatus.OK);
        }
        try {
            int result = _chatService.operateChatBranchStage(_request, BaseEnum.ChatBranchStageOperateType.Start.getChatBranchStageOperateType(), userId());
            _baseResponse = ResponseError(null, "参数格式错误");
            _baseResponse.setMessage("操作失败");
            _baseResponse.setSuccess(BaseEnum.ApiResult.Failure.getApiResult());

            if (result > 0) {
                _baseResponse.setMessage("操作成功");
                _baseResponse.setSuccess(BaseEnum.ApiResult.Success.getApiResult());
            }
            return new ResponseEntity(_baseResponse, HttpStatus.OK);

        } catch (Exception ex) {
            _baseResponse.setData(ex);
            ex.printStackTrace();
        }
        return new ResponseEntity(_baseResponse, HttpStatus.OK);
    }

    //结束分支
    @RequestMapping("finishbranch")
    public ResponseEntity<?> finishChatBranchStage(@RequestBody(required = false) ChatBranchStageRequest _request) {
        BaseResponse _baseResponse = new BaseResponse();
        if (_request == null) {
            _baseResponse = ResponseError(null, "参数格式错误");
            return new ResponseEntity(_baseResponse, HttpStatus.OK);
        }
        try {
            int result = _chatService.operateChatBranchStage(_request, BaseEnum.ChatBranchStageOperateType.UnStart.getChatBranchStageOperateType(), userId());
            _baseResponse = ResponseError(null, "参数格式错误");
            _baseResponse.setMessage("操作失败");
            _baseResponse.setSuccess(BaseEnum.ApiResult.Failure.getApiResult());

            if (result > 0) {
                _baseResponse.setMessage("操作成功");
                _baseResponse.setSuccess(BaseEnum.ApiResult.Success.getApiResult());
            }
            return new ResponseEntity(_baseResponse, HttpStatus.OK);

        } catch (Exception ex) {
            _baseResponse.setData(ex);
            ex.printStackTrace();
        }
        return new ResponseEntity(_baseResponse, HttpStatus.OK);
    }


    ///get questtion list
    @RequestMapping("questions")
    public ResponseEntity<?> getQuestions() {
        DataResponse _dataResponse = new DataResponse();
        try {
            List<CrmQuestion> _result = _chatService.getQuestions();
            _dataResponse.setData(_result);
        } catch (Exception ex) {
            ex.printStackTrace();
            _dataResponse.setData(ex);
        }
        return new ResponseEntity(_dataResponse, HttpStatus.OK);
    }

    //get answer
    @RequestMapping("answers")
    public ResponseEntity<?> getAnswers(@RequestBody(required = false) GetAnswerRequest _request) {
        DataResponse _dataResponse = new DataResponse();
        try {
            List<CrmAnswer> _result = _chatService.getAansere(_request.getQuestionid());
            _dataResponse.setData(_result);
        } catch (Exception ex) {
            ex.printStackTrace();
            _dataResponse.setData(ex);
        }
        return new ResponseEntity(_dataResponse, HttpStatus.OK);
    }

    @RequestMapping("imcallback")
    public ResponseEntity<?> imCallBack(
            @RequestParam(required = false) Map<String, Object> _params,
            @RequestBody(required = false) CrmChatCallBack _request
    ) {
        DataResponse _dataResponse = new DataResponse();
        try {
            Boolean valid = false;
            Object objSdkAppid = _params.get("SdkAppid");
            if (objSdkAppid != null) {
                Long sdkAppid = Long.parseLong(objSdkAppid.toString());
                if (sdkAppid == _imConfig.getSdkappid()) {
                    valid = true;
                    _dataResponse.setData("fail");
                }
            }

            if (valid == true && _request != null) {
                _dataResponse.setData("ok");
                Object objOptPlatform = _params.get("OptPlatform");
                ChatCallBackMessage req = new ChatCallBackMessage();

                int userId = Integer.parseInt(_request.getFrom_Account());
                req.setGroupid(_request.getGroupId());
                req.setRecstatus(1);
                req.setReccreator(userId);

                Date dt = Calendar.getInstance().getTime();
                SimpleDateFormat _dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date _formatNow = _dataFormat.parse(_dataFormat.format(dt));
                req.setCreatetime(new Date());
                req.setSender(userId);
                req.setMsgtime(_request.getMsgTime());
                req.setRandom(_request.getRandom());
                req.setMsgseq(_request.getMsgSeq());
                int callbacktype = BaseEnum.MsgCallBackType.getMsgCallBackTypeStr(_request.getCallbackCommand());
                req.setCallbacktype(callbacktype);
                req.setDevice(BaseEnum.ClientType.getClientTypeStr(objOptPlatform.toString()));
                int category = BaseEnum.MsgCallBackContentCategory.getMsgCallBackContentCategoryStr(_request.getType());
                req.setMsgcategory(category);
                if (_request.getMsgBody() != null && _request.getMsgBody().size() > 0) {
                    String content = "";
                    for (CrmChatCallBackBody body : _request.getMsgBody()) {
                        int type = BaseEnum.MsgCallBackContentType.getMsgCallBackContentTypeStr(body.getMsgType());
                        req.setMsgtype(type);
                        //这里只保存文本类型消息
                        if (type == BaseEnum.MsgCallBackContentType.Text.getMsgCallBackContentType()) {
                            content += body.getMsgContent().get("Text");
                        }

                    }
                    req.setContent(content);

                    Object body = JSONArray.toJSON(_request.getMsgBody());
                    req.setMsgcontent(body.toString());
                    _chatService.chatCallBackMessage(req, userId);
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            _dataResponse.setData(ex);
        }
        return new ResponseEntity(_dataResponse, HttpStatus.OK);
    }
}
